#!/usr/bin/env python

import bluetooth
from bluetooth import *
from subprocess import *
import sys


def _get_all_serial_services(addr = None):
    # the uuid of Serial Port Profile
    uuid = "1101"
    return  find_service( uuid = uuid, address = addr)

def get_all_bt_devices():
    return bluetooth.discover_devices(lookup_names = True)

def _show_zenity(device_list):
    #zenity --list m1 m2 m3 m4 m5 --text=text  --title=titl --column=asdd
    args = [ 'zenity' ,
             '--text="Choose bluetooth device"', 
             '--title="AWESOME-O Bluetooth chooser"', 
             '--column="Choose bt"',
             '--list' ]
    for addr, name in device_list:
        args.append(name)
    try:
        zenity = Popen(args, stdout=PIPE)
        sout, serr = zenity.communicate()
        choice = sout.strip()
        print "received [", choice, "] from zenity"
        for addr, name in device_list:
            if choice == name:
                return (addr, name)
    except:
        pass
    return None

def choose_bt_device_and_connect():
    choice_addr, choice_name = _show_zenity(get_all_bt_devices())
    service_matches = _get_all_serial_services(choice_addr)
    if len(service_matches) == 0:
        print "couldn't find the SampleServer service =("
        return None

    first_match = service_matches[0]
    port = first_match["port"]
    name = first_match["name"]
    host = first_match["host"]
    
    
    print "connecting to \"%s\" on %s" % (name, host)

    # Create the client socket
    sock=BluetoothSocket( RFCOMM )
    sock.connect((host, port))
    return sock

if __name__ == "__main__":
    sock = choose_bt_device_and_connect()
    
    print "connected.  type stuff"
    while True:
        data = raw_input()
        if len(data) == 0: break
        sock.send(data + "\n")
    sock.close()
